package org.jsbd.boss.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jsbd.boss.common.DataGridModel;
import org.jsbd.boss.common.ResponseMapUtils;
import org.jsbd.boss.common.ResponseUtils;
import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.domian.NewExecutionGroupMarkVO;
import org.jsbd.boss.domian.channel.ActionType;
import org.jsbd.boss.domian.channel.ClientRunInfo;
import org.jsbd.boss.domian.channel.ClientTaskInfo;
import org.jsbd.boss.domian.channel.LocationInfo;
import org.jsbd.boss.service.ISimulatorListenService;
import org.jsbd.boss.service.ISimulatorTaskService;
import org.jsbd.boss.util.CacheKey;
import org.jsbd.boss.util.SortList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping("/qyChannelSimulatorListen")
public class QyChannelSimulatorListenController{

	private static final Logger LOGGER=LoggerFactory.getLogger(QyChannelSimulatorListenController.class);
	
	@Autowired
	private ISimulatorListenService simulatorListenService;
	@Autowired
	private ISimulatorTaskService simulatorTaskService;
	@Resource
	private RedisClient<String, Object> redisClient;

	/**
	 * 列表页面
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "listModel")
	public String showQyChannelSimulatorListenList(Model model) throws Exception {
		return "/qyChannelSimulatorListen/qyChannelSimulatorListenList";
	}

	@RequestMapping(value = "getQyChannelSimulatorListenListPage")
	@ResponseBody
	public Map<String, Object> getQyChannelSimulatorListenListPage(DataGridModel page,ClientRunInfo runInfo) throws Exception {
		try{
			List<ClientRunInfo> runInfoList=simulatorListenService.getSimulatorList(runInfo);
			
			Map<String, Object> results = new HashMap<String, Object>();
			int len=runInfoList.size();
			if(page.getCurrentRow()>=len){
				results.put("total", 0);
				results.put("rows",new ArrayList<ClientRunInfo>(0));
				return results;
			}
			
			if(page.getCurrentRow()+page.getRows()<len){
				len=page.getCurrentRow()+page.getRows();
			}
			
			List<ClientRunInfo> showList=runInfoList.subList(page.getCurrentRow(), len);
			results.put("total", runInfoList.size());
			results.put("rows",showList);
			
			return results;
		}catch(Exception e){
			LOGGER.error("",e);
			throw e;
		}
	}
	
	@RequestMapping(value = "publishTask")
	@ResponseBody
	public Map<String, Object> publishTask(String uuids,int orderType,String taskContent) throws Exception {
		if(StringUtils.isBlank(uuids)){
			return ResponseMapUtils.responseFail("uuids参数不能为空");
		}
		
		ClientTaskInfo taskInfo=new ClientTaskInfo();
		taskInfo.setTaskId(UUID.randomUUID().toString().replace("-", ""));
		taskInfo.setOrderType(orderType);
		if(StringUtils.isNotBlank(taskContent)){
			taskInfo.setTaskContent(JSON.parseObject(taskContent));
		}
		
		List<Object> keyList=new ArrayList<Object>();
		Map<String,Object> dataMap=new HashMap<String,Object>();
		String[] uuidArr=uuids.split(",");
		for(String uuid:uuidArr){
			keyList.add(uuid);
			dataMap.put(uuid, taskInfo);
		}
		
		boolean hasTask=simulatorListenService.hasTask(keyList);
		if(hasTask){
			return ResponseMapUtils.responseFail("以选模拟器已经有任务在执行了，请重新选择");
		}
		
		simulatorListenService.addTask(dataMap);
		
		return ResponseMapUtils.responseSuccess();
	}
	
	@RequestMapping(value = "batchPublishTask")
	@ResponseBody
	public Map<String, Object> batchPublishTask(String uuids,int orderType,String taskContent) throws Exception {
		if(StringUtils.isBlank(uuids)){
			return ResponseMapUtils.responseFail("uuids参数不能为空");
		}
		
		List<String> list = (List<String>) redisClient.getList(CacheKey.UPGRADE_SYSTEM_LIST);
		Set<String> set = new HashSet<String>(); 
		set.addAll(list);
		
		String[] uuidArr=uuids.split(",");
		for(String uuid:uuidArr){
			if (set.contains(uuid)) {
				continue;
			}
			redisClient.putToQueue(CacheKey.UPGRADE_SYSTEM_LIST, uuid);
		}
		
		redisClient.put(CacheKey.UPGRADE_SYSTEM_ORDER_TYPE, orderType);
		redisClient.put(CacheKey.UPGRADE_SYSTEM_TASK_CONTENT, taskContent);
		
		return ResponseMapUtils.responseSuccess();
	}
	
	
	@RequestMapping(value = "removeTask")
	@ResponseBody
	public Map<String, Object> removeTask(String uuids) throws Exception {
		if(StringUtils.isBlank(uuids)){
			return ResponseMapUtils.responseFail("uuid为必填参数，请重试");
		}
		simulatorListenService.removeTask(uuids.split(","));
		return ResponseMapUtils.responseSuccess();
	}
	
	@RequestMapping(value = "clearLocation")
	@ResponseBody
	public Map<String, Object> clearLocation(){
		simulatorListenService.clearLocation();
		return ResponseMapUtils.responseSuccess();
	}
	
	@RequestMapping(value = "clearOffline")
	@ResponseBody
	public Map<String, Object> clearOffline(String uuids){
		simulatorListenService.clearOffline(uuids);
		return ResponseMapUtils.responseSuccess();
	}
	
	

	@RequestMapping(value = "viewTask")
	@ResponseBody
	public Map<String, Object> viewTask(String taskId){
		Map<String,Object> resultMap=ResponseMapUtils.responseSuccess();
		resultMap.put("data", simulatorTaskService.getSimulatorTask(taskId));
		return resultMap;
	}
	
	@RequestMapping(value = "/setNum")
	@ResponseBody
	public void setNum(Integer upgradeSystemNum, Integer upgradeSystemIntervalTime, HttpServletResponse response){
		try {
			redisClient.put(CacheKey.UPGRADE_SYSTEM_NUM, upgradeSystemNum);
			redisClient.put(CacheKey.UPGRADE_SYSTEM_INTERVAL_TIME, upgradeSystemIntervalTime);
			ResponseUtils.responseSuccess(response);
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
			ResponseUtils.responseFailure(response);
		}
		
	}
	
	/**
	 * 模拟器机柜在线/离线数量列表页面
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "qyChannelLocationNumList")
	public String showQyChannelLocationNumList(Model model) throws Exception {
		return "/qyChannelSimulatorListen/qyChannelLocationNumList";
	}
	
	@RequestMapping(value = "getQyChannelLocationNumListPage")
	@ResponseBody
	public Map<String, Object> getQyChannelLocationNumListPage(LocationInfo locationInfo) throws Exception {
		try{
			List<LocationInfo> list=simulatorListenService.getLocationNumList(locationInfo);
			
			SortList<LocationInfo> sortList = new SortList<LocationInfo>();  
			sortList.Sort(list, "getLocation", "asc"); 
			
			Map<String, Object> results = new HashMap<String, Object>();
			results.put("total", list.size());
			results.put("rows",list);
			
			return results;
		}catch(Exception e){
			LOGGER.error("",e);
			throw e;
		}
	}
	
	/**
	 * 查询重复MAC
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "showMacRepeatList")
	public String showMacRepeatList(Model model) throws Exception {
		return "/qyChannelSimulatorListen/showMacRepeatList";
	}
	
	/**
	 * 重复MAC数据
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "showMacRepeatListJson")
	@ResponseBody
	public Map<String, Object> showMacRepeatListJson(DataGridModel page, ClientRunInfo runInfo) throws Exception {
		try{
			List<ClientRunInfo> runInfoList=simulatorListenService.getMacRepeatList(runInfo);
			
			Map<String, Object> results = new HashMap<String, Object>();
			int len = runInfoList.size();
			if(page.getCurrentRow() >= len){
				results.put("total", 0);
				results.put("rows",new ArrayList<ClientRunInfo>(0));
				return results;
			}
			
			if(page.getCurrentRow() + page.getRows() < len){
				len = page.getCurrentRow() + page.getRows();
			}
			
			List<ClientRunInfo> showList = runInfoList.subList(page.getCurrentRow(), len);
			
			SortList<ClientRunInfo> sortList = new SortList<ClientRunInfo>();  
			sortList.Sort(showList, "getClientMac", "asc");  
			
			results.put("total", runInfoList.size());
			results.put("rows",showList);
			
			return results;
		}catch(Exception e){
			LOGGER.error("",e);
			throw e;
		}
	}
	
}
